//
//  AppDelegate.m
//  ChartsDemo
//
//  Created by 李光尧 on 2021/3/19.
//

#import "AppDelegate.h"
#import "AAChartController.h"
//#import "HomeViewController.h"
#import "ARTScanDeviceController.h"
#import "ARTWelcomeController.h"
#import "ARTMainTabController.h"
#import <UserNotifications/UserNotifications.h>
#import "ARTWathDataAnalysis.h"
#import <mach-o/dyld.h>
#import <ChartsDemo-Swift.h>

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate

- (UIWindow *)launchWindow {
    if (!_launchWindow) {
        _launchWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _launchWindow.backgroundColor = [UIColor clearColor];
        _launchWindow.windowLevel = UIWindowLevelAlert;
    }
    return _launchWindow;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
//#ifndef __OPTIMIZE__
/// Debug
//    [self redirectNSlogToDocumentFolder];
//#else
///// release
//#endif

    [self setUpMainWindow];
    [self setUpLaunchWindow];
    
//    // bugly
//    BuglyConfig *config = [[BuglyConfig alloc]init];
//    config.debugMode = YES;
//    config.consolelogEnable = NO;
//    // 设置自定义日志上报的级别，默认不上报自定义日志
//    config.reportLogLevel = BuglyLogLevelWarn;
//    [Bugly startWithAppId:@"fc0d89c0c7" config:config];
    
    // 注册本地通知
//    [self registLocationNotification];
    
    [self safaMethod];
    
//    NSNumber *aaa = @(0xB40BBE37);
//    NSData *dataaa = [ASFHConverter convert_16Data_with_16String:aaa];
//    NSLog(@"asdf----%d",aaa.intValue);
//    NSLog(@"========as======%ld",(long)[[ARTSafeHelper new] asyncmethodWithValue:999999]);
//    Byte temp[20] = {0xfe,0x5a,0x14,0x1d,0xcf,0x27,0x36,0x63,0xe0,0xba,0x86,0x42,0x29,0x60,0x60,0xc2,0x6f,0x95,0x3c,0x36};
//    NSInteger a = [[ARTSafeHelper new] resultForAppWithValue:[NSData dataWithBytes:temp length:20]];
//    NSLog(@"-----aa---%@",@(a));
    
//    NSString *pubkey = @"-----BEGIN RSA PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTbZ6cNH9PgdF60aQKveLz3FTalyzHQwbp601y77SzmGHX3F5NoVUZbdK7UMdoCLK4FBziTewYD9DWvAErXZo9BFuI96bAop8wfl1VkZyyHTcznxNJFGSQd/B70/ExMgMBpEwkAAdyUqIjIdVGh1FQK/4acwS39YXwbS+IlHsPSQIDAQAB-----END RSA PUBLIC KEY-----";
//    NSString *prikey = @"-----BEGIN RSA PRIVATE KEY-----MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANNtnpw0f0+B0XrRpAq94vPcVNqXLMdDBunrTXLvtLOYYdfcXk2hVRlt0rtQx2gIsrgUHOJN7BgP0Na8AStdmj0EW4j3psCinzB+XVWRnLIdNzOfE0kUZJB38HvT8TEyAwGkTCQAB3JSoiMh1UaHUVAr/hpzBLf1hfBtL4iUew9JAgMBAAECgYA1tGeQmAkqofga8XtwuxEWDoaDS9k0+EKeUoXGxzqoT/GyiihuIafjILFhoUA1ndf/yCQaG973sbTDhtfpMwqFNQq13+JAownslTjWgr7Hwf7qplYW92R7CU0v7wFfjqm1t/2FKU9JkHfaHfb7qqESMIbO/VMjER9o4tEx58uXDQJBAO0O4lnWDVjr1gN02cqvxPOtTY6DgFbQDeaAZF8obb6XqvCqGW/AVms3Bh8nVlUwdQ2K/xte8tHxjW9FtBQTLd8CQQDkUncO35gAqUF9Bhsdzrs7nO1J3VjLrM0ITrepqjqtVEvdXZc+1/UrkWVaIigWAXjQCVfmQzScdbznhYXPz5fXAkEAgB3KMRkhL4yNpmKRjhw+ih+ASeRCCSj6Sjfbhx4XaakYZmbXxnChg+JB+bZNz06YBFC5nLZM7y/n61o1f5/56wJBALw+ZVzE6ly5L34114uG04W9x0HcFgau7MiJphFjgUdAtd/H9xfgE4odMRPUD3q9Me9LlMYK6MiKpfm4c2+3dzcCQQC8y37NPgpNEkd9smMwPpSEjPW41aMlfcKvP4Da3z7G5bGlmuICrva9YDAiaAyDGGCK8LxC8K6HpKrFgYrXkRtt-----END RSA PRIVATE KEY-----";
//    NSString *comeP= [RSA encryptString:@"123" publicKey:pubkey];
//    NSLog(@"加密前=%@",comeP);
//    NSString *come = [RSA decryptString:comeP publicKey:prikey];
//    NSLog(@"解密后=%@",come);
    
    
//    RSAEncryptor* rsaEncryptor = [[RSAEncryptor alloc] init];
//    NSString* publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
//    NSString* privateKeyPath = [[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"p12"];
//    [rsaEncryptor loadPublicKeyFromFile: publicKeyPath];
//    [rsaEncryptor loadPrivateKeyFromFile: privateKeyPath password:@"112200"];    // 密码
//
//    NSString* restrinBASE64STRING = [rsaEncryptor rsaEncryptString:@"你好，世界"];
//    NSLog(@"加密后: %@", restrinBASE64STRING);     //加密
//    NSString* decryptString = [rsaEncryptor rsaDecryptString: restrinBASE64STRING];//解密
//    NSLog(@"解密后: %@", decryptString);
    
//    //原始数据
//    NSString *originalString = @"这是一段将要使用'.der'文件加密的字符串!";
//    
//    //使用.der和.p12中的公钥私钥加密解密
//    NSString *public_key_path = [[NSBundle mainBundle] pathForResource:@"public_key.der" ofType:nil];
//    NSString *private_key_path = [[NSBundle mainBundle] pathForResource:@"private_key.p12" ofType:nil];
//    
//    NSString *encryptStr = [RSAEncryptor encryptString:originalString publicKeyWithContentsOfFile:public_key_path];
//    NSLog(@"加密前:%@", originalString);
//    NSLog(@"加密后:%@", encryptStr);
//    NSLog(@"解密后:%@", [RSAEncryptor decryptString:encryptStr privateKeyWithContentsOfFile:private_key_path password:@"123456"]);
    
    /*
    //原始数据
    NSMutableString *originalString = [NSMutableString new];
    for (int i = 0; i < 100000; i++) {
        [originalString appendString:@(i).stringValue];
    }
    
    //使用字符串格式的公钥私钥加密解密
    NSString *encryptStr = [RSAEncryptor encryptSubsectionString:originalString publicKey:ART_Pubkey];
    
//    NSLog(@"加密前:%@", originalString);
//    NSLog(@"加密后:%@", encryptStr);
    
    NSString *decryptStr = [RSAEncryptor decryptSubsectionString:encryptStr privateKey:ART_Prikey];
//    NSLog(@"解密后:%@", decryptStr);
    
    NSString *filePath = [J_Path_Document stringByAppendingPathComponent:@"History"];
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        //如果不存在
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];//创建文件夹
    }
    
    NSString *dataFileName = @"encryptStr";
    NSString *watchFilePath = [filePath stringByAppendingPathComponent:dataFileName];
    BOOL isSave = [encryptStr writeToFile:watchFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSave) {
        NSLog(@"存储成功");
    }
    
    NSString *dataFileName1 = @"decryptStr";
    NSString *watchFilePath1 = [filePath stringByAppendingPathComponent:dataFileName1];
    BOOL isSave1 = [decryptStr writeToFile:watchFilePath1 atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSave1) {
        NSLog(@"存储成功1");
    }
    
    NSString *dataFileName3 = @"originalString";
    NSString *watchFilePath3 = [filePath stringByAppendingPathComponent:dataFileName3];
    BOOL isSave3 = [originalString writeToFile:watchFilePath3 atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSave3) {
        NSLog(@"存储成功1");
    }
     */
    
    return YES;
}

//- (void)redirectNSlogToDocumentFolder{
//    UIDevice *device = [UIDevice currentDevice];
//    if ([[device model] isEqualToString:@"Simulator"]) {
//        return;
//    }
//    NSLog(@"保存日志");
//    NSString *documentDirectory = J_Path_Document;
//    NSString *fileName = [NSString stringWithFormat:@"test.txt"];
//    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
//    // Delete existing files
//    NSFileManager *defaultManager = [NSFileManager defaultManager];
//    [defaultManager removeItemAtPath:logFilePath error:nil];
//    //Enter the log into the file
//    freopen([logFilePath cStringUsingEncoding:NSUTF8StringEncoding], "a+", stdout);
//    freopen([logFilePath cStringUsingEncoding:NSUTF8StringEncoding], "a+", stderr);
//}

//===============安全==================
- (void)exitApplication {
    exit(0);
}

- (void)safaMethod{
    if([self isJailBroken]) {
        NSLog(@"已越狱");
        [[ARTNavigation currentViewController] lq_showAlertControllerWithMessage:@"手机已越狱，清注意安全！" okHandle:^{
            [self exitApplication];
        }];
        return;
    }else{
        NSLog(@"未越狱");
    }
    if([self checkMach_O]) {
        NSLog(@"二次打包");
        [[ARTNavigation currentViewController] lq_showAlertControllerWithMessage:@"APP完整性被破坏，清注意安全！" okHandle:^{
            [self exitApplication];
        }];
        return;
    }else{
        NSLog(@"Mach_O 正常");
    }
    if([self checkCodeSignWithProvisionID:@"6TKNR3ZG7Y"]) {
        NSLog(@"teamid 正常");
    }else{
        NSLog(@"APP被篡改-重签名");
        [[ARTNavigation currentViewController] lq_showAlertControllerWithMessage:@"APP被篡改，清注意安全！" okHandle:^{
            [self exitApplication];
        }];
        return;
    }
    if (isInjected0() || isInjected1()) {
        NSLog(@"APP被动态注入");
        [[ARTNavigation currentViewController] lq_showAlertControllerWithMessage:@"APP有注入风险！" okHandle:^{
            [self exitApplication];
        }];
        return;
    }
}

// 动态注入
BOOL isInjected0(void){
    int count = _dyld_image_count();//获取加载image的数量
    if (count > 0) {
        for (int i = 0; i < count; i++) {//遍历所有的image_name。判断是否有DynamicLibraries
            const char * dyld = _dyld_get_image_name(i);
            if (strstr(dyld, "DynamicLibraries")) {
                return YES;
            }
        }
    }
    return NO;
}
BOOL isInjected1(void){//检测环境变量是否有DYLD_INSERT_LIBRARIES
//    char* env = getenv("DYLD_INSERT_LIBRARIES");
//    if(env != NULL){
//        return YES;
//    }
    return NO;
}


// 越狱检测
const char* jailbreak_tool_pathes[] = {
    "/Applications/Cydia.app",
    "/Library/MobileSubstrate/MobileSubstrate.dylib",
    "/bin/bash",
    "/usr/sbin/sshd",
    "/etc/apt"
};
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
- (BOOL)isJailBroken
{
    if ([self isSimulator] == YES)
    {
        return NO;
    }

    for (int i=0; i<ARRAY_SIZE(jailbreak_tool_pathes); i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jailbreak_tool_pathes[i]]]) {
            NSLog(@"The device is jail broken!");
            return YES;
        }
    }
    NSLog(@"The device is NOT jail broken!");
    return NO;
}


- (BOOL)isSimulator {
#if TARGET_OS_SIMULATOR
    return YES;
#else
    return NO;
#endif
}

//- (BOOL)isYueYu{
//    NSError *error;
//    NSString *stringToWrite = @"Jailbreak Test";
//    [stringToWrite writeToFile:@"/private/jailbreak_test.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
//    
//    if (!error) {
//        //删除测试文件
//        [[NSFileManager defaultManager] removeItemAtPath:@"/private/jailbreak_test.txt" error:nil];
//        return NO;
//    }
//    return YES;
//}

//判断Mach-O文件否被篡改
- (BOOL)checkMach_O
{
    NSBundle *bundle = [NSBundle mainBundle];
    NSDictionary *info = [bundle infoDictionary];
    if ([info objectForKey: @"SignerIdentity"] != nil) {
        //存在这个key，则说明被二次打包了
        return YES;
    }

    return NO;
}

/**
 重签名检测
@param provisionID 开发者的teamid
 */
- (BOOL)checkCodeSignWithProvisionID:(NSString *)provisionID
{
    // 描述文件路径
    NSString *embeddedPath = [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:embeddedPath]) {

        // 读取application-identifier
        NSString *embeddedProvisioning = [NSString stringWithContentsOfFile:embeddedPath encoding:NSASCIIStringEncoding error:nil];
        NSArray *embeddedProvisioningLines = [embeddedProvisioning componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

        for (int i = 0; i < [embeddedProvisioningLines count]; i++) {
            if ([[embeddedProvisioningLines objectAtIndex:i] rangeOfString:@"application-identifier"].location != NSNotFound) {

                NSInteger fromPosition = [[embeddedProvisioningLines objectAtIndex:i+1] rangeOfString:@"<string>"].location+8;

                NSInteger toPosition = [[embeddedProvisioningLines objectAtIndex:i+1] rangeOfString:@"</string>"].location;

                NSRange range;
                range.location = fromPosition;
                range.length = toPosition - fromPosition;

                NSString *fullIdentifier = [[embeddedProvisioningLines objectAtIndex:i+1] substringWithRange:range];

                //                NSLog(@"%@", fullIdentifier);

                NSArray *identifierComponents = [fullIdentifier componentsSeparatedByString:@"."];
                NSString *appIdentifier = [identifierComponents firstObject];

                // 对比签名ID
                if (![appIdentifier isEqual:provisionID])
                {
                    return NO;
                }
                else
                {
                    return YES;
                }
            }
        }
    }
    return YES;
}

//===============安全==================

/// 注册本地通知
- (void)registLocationNotification{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"***************************授权本地通知成功");
            }
        }];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            
        }];
    }
}

- (void)setUpMainWindow {
    //AAChartController ViewController HomeViewController ARTScanDeviceController ARTWelcomeController
    
    ARTScanDeviceController *vc = [ARTScanDeviceController new];
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
//    nav.navigationBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"i_return_black"];
//    nav.navigationBar.backIndicatorImage = [UIImage imageNamed:@"i_return_black"];
    
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
}

- (void)setUpLaunchWindow {
    ARTWelcomeController *vc = [[ARTWelcomeController alloc] init];
    self.launchWindow.rootViewController = vc;
    [self.launchWindow makeKeyAndVisible];
}

- (void) endBackgroundTask{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    AppDelegate *weakSelf = self;
    dispatch_async(mainQueue, ^(void) {
        AppDelegate *strongSelf = weakSelf;
        if (strongSelf != nil){
            [[UIApplication sharedApplication]endBackgroundTask:self.backgroundTaskIdentifier];
            // 销毁后台任务标识符
            strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
        }
    });
}

- (void)applicationWillResignActive:(UIApplication *)application {
     NSLog(@"--- %s ---",__func__);
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
   NSLog(@"--- %s ---",__func__);
    self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^(void) {
        [self endBackgroundTask];
    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
   NSLog(@"--- %s ---",__func__);
    // 检测是否需要强制更新
//    [ARTVersionUpdateHelper detectForcedUpdate];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  NSLog(@"--- %s ---",__func__);
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
     NSLog(@"--- %s ---",__func__);
}

- (void)applicationWillTerminate:(UIApplication *)application {
    NSLog(@"--- %s ---",__func__);
}

@end
